/* eslint no-undef: 0 */
import axios from 'axios'
import qs from 'qs'
import { commonLoading } from '@govcloud/gsd-web-core-ui'
import config from '@govcloud/gsd-web-core-config'

// 默认配置
axios.defaults.timeout = 15000
axios.defaults.headers['Content-Type'] = 'application/json'

// 普通请求实例
const request = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL + process.env.VUE_APP_API_ROUTER,
  maxRedirects: 0
})

// 网关请求
const requestAccessLayer = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL + process.env.VUE_APP_API_ACCESS_LAYER_URL,
  maxRedirects: 0
})

// form-data类型请求实例
const requestFd = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL + process.env.VUE_APP_API_ROUTER,
  method: 'post',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  transformRequest: [
    function(data) {
      Object.keys(data).forEach(key => {
        if (typeof data[key] === 'object') {
          data[key] = JSON.stringify(data[key])
        }
      })
      return qs.stringify(data)
    }
  ]
})

/**
 * 拦截器成功回调
 * 所有接口返回0才正常返回resolve
 * 非0都reject出去
 * @param res
 * @returns {*}
 */
function resolve(res) {
  const data = res.data || {}
  if (res.config && !res.config.hideLoading) {
    commonLoading.hide()
  }

  if (+data[config.apiReturnDefine.errcode] !== 0) {
    // 调试模式下，非0统一提示
    if (config.debugModel) {
      console.warn(
        '接口非0啦！错误信息看这里！',
        '\n responseURL:',
        res.request.responseURL,
        '\n data: ',
        res.data,
        '\n all message: ',
        res
      )
    }

    return Promise.reject(data)
  }

  if (typeof data[config.apiReturnDefine.data] !== 'undefined') {
    return data[config.apiReturnDefine.data]
  }
  return data
}

// 失败，一般是网络错误
function reject(error) {
  if (error.config && !error.config.hideLoading) {
    commonLoading.hide()
  }
  console.error('=====> response error: ', error.response)
  return Promise.reject(error)
}

request.interceptors.request.use(function(conf) {
  if (!conf.hideLoading) {
    commonLoading.show('加载中，请稍候...')
  }
  return conf
})


request.interceptors.response.use(resolve, reject)
requestAccessLayer.interceptors.response.use(resolve, reject)
requestFd.interceptors.response.use(resolve, reject)

export { request, requestFd, requestAccessLayer }
